﻿using System.Linq.Expressions;

namespace HuaweiCloud.Dotnet.Samples.Common
{
    public abstract class DocApplicationServiceBase<T> : IDocApplicationService<T> where T : BaseComponent
    {
        protected readonly IDocRepository<T> _repository;
        public DocApplicationServiceBase(IDocRepository<T> repository)
        {
            _repository = repository;
        }

        public virtual async Task AddAsync(T t, CancellationToken token = default)
        {
            await _repository.AddAsync(t, token);
        }

        public virtual async Task DeleteAsync<TID>(TID id, CancellationToken token = default) where TID : notnull
        {
            var item = await GetAsync(id, token);
            if(item != null)
                await _repository.DeleteAsync(item, token);
        }

        public virtual async Task<T?> GetAsync<TID>(TID id, CancellationToken token = default) where TID : notnull
        {
            return await _repository.GetByIdAsync(id, token);
        }

        public virtual async Task<IList<T>> ListAsync(Expression<Func<T, bool>>? filter = null, CancellationToken token = default)
        {
            return await _repository.ListAsync(filter, token);
        }

        public virtual async Task UpdateAsync(T t, CancellationToken token = default)
        {
            await _repository.UpdateAsync(t, token);
        }
    }
}
